import React, { PureComponent } from 'react';
// import { connect } from 'dva';
import style from "styled-components";
import {
  Input,
  Button,
  Form,
  Select,
  Card,
  Row,
  Col,
  Icon,
  Modal,
  DatePicker,
  message,
} from 'antd';
import Drawer from 'react-motion-drawer';
import moment from 'moment';

import {
  getDictInformation, //公共信息
  //systemPerCerBaseInfoFind,//编辑证书-查看证书-展示当前证书信息
  systemPerCerBaseInfoGet,//编辑证书-查看证书-展示当前证书信息-完整模板
  systemPerCerBaseInfoUpdate,//编辑证书-修改-保存用户证书
  //systemConfigPerCerInfoFindListByPercertype,//新增证书-查看证书特殊信息字段；编辑证书-查看已创建证书特殊信息字段和字段值
} from "../../../services/api";

const FormItem = Form.Item;
const { Option } = Select;
//const { RangePicker } = DatePicker;
// const RadioGroup = Radio.Group;
//const { TextArea } = Input;
const dateFormat = 'YYYY/MM/DD';

message.config({
  top: 100,
  right: 5,
  duration: 2,
});

// @connect(state => ({ profile: state.profile }))
@Form.create()

// 编辑证书-抽屉
export default class EditCertificateDrawer extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      editCertificateOpen: this.props.visiable,//抽屉
      currentId: 0,//当前ID
      perCerType: [],//证书类型
      perCerlevel: [],//证书等级
      //certificateType: '1',
      //specialFields: [],
      // editList: this.props.editList,
      // editSpecialArray: this.props.editSpecialArray,
      editList: {
        perCerType: '',//证书类型
        cerNo: '',//证书编号
        licenceOrg: '',//发证机关
        licenceOrgNo: '',//发证机关编号
        licenceDate: '',//发证日期
        //cerNo:'',//证书类型
      },
      editSpecialArray: [],
    };

  }
  /******************************生命周期******************************/

  componentDidMount = () => {
    this.getAllType();//获取所有类型
    // this.getSpecialFields();//特殊字段
    //this.showCertificateInfo(this.state.currentId);//查看证书
  }
  componentWillReceiveProps(props) {
    this.setState({ editCertificateOpen: props.visiable });
    this.setState({ currentId: props.currentId }, () => {
      if (props.currentId !== 0) {
        // this.showCertificateInfo(props.currentId);//查看证书
        console.log('编辑-componentWillReceiveProps-props.currentId', props.currentId);
        console.log('编辑-componentWillReceiveProps-props.visible', this.state.editCertificateOpen);
        systemPerCerBaseInfoGet({ perCerId: this.state.currentId }).then((res) => {
          console.log('查看当前证书-res:', res);
          this.setState(
            {
              editList: res.data,
              editSpecialArray: JSON.parse(res.data.list),
            }
          );
          console.log("编辑List", this.state.editList);
          console.log("编辑特殊字段", this.state.editSpecialArray);
        }, (err) => {
          console.log('查看当前证书-错误信息', err);
        });
      }
      // console.log("编辑-当前ID-componentWillReceiveProps", this.state.currentId);
    });
  }
  /******************************ajax请求******************************/
  //获得公共信息
  getAllType = () => {
    getDictInformation({ codeTypes: [' perCerType', ' perCerlevel'] }).then((res) => {
      console.log('证书字典表-res:', res);
      //判断获取数据是否为空
      if (res.data) {
        const allTypeData = res.data;
        this.setState({
          perCerType: allTypeData.perCerType,
          perCerlevel: allTypeData.perCerlevel,
        });
      }
    });
  };

  //编辑证书-查看证书特殊信息字段
  // getSpecialFields = () => {
  //   const perCerType = this.state.certificateType;
  //   systemConfigPerCerInfoFindListByPercertype({ perCerType }).then((res) => {
  //     console.log('编辑特殊字段-res:', res);
  //     if (res.data) {
  //       this.setState({
  //         specialFields: res.data,
  //       });
  //     }
  //     console.log("编辑-特殊字段数组", this.state.specialFields);
  //   }, (err) => {
  //     console.log('编辑特殊字段-错误信息', err);
  //   });
  // }

  //查看证书
  // showCertificateInfo = (perCerId) => {
  //   // const perCerId = this.state.currentId;
  //   systemPerCerBaseInfoGet({ perCerId }).then((res) => {
  //     console.log('查看当前证书-res:', res);
  //     this.setState(
  //       {
  //         editList: res.data,
  //         editSpecialArray: JSON.parse(res.data.list),
  //       }
  //     );
  //     console.log("编辑List", this.state.editList);
  //     console.log("编辑特殊字段", this.state.editSpecialArray);
  //   }, (err) => {
  //     console.log('查看当前证书-错误信息', err);
  //   });
  // }

  /******************************相关事件******************************/
  // changeCertificateType = (value) => {
  //   console.log("编辑-证书类型切换：", value);
  //   if (value) {
  //     this.setState({
  //       specialFields: [],
  //     });
  //     systemConfigPerCerInfoFindListByPercertype({ perCerType: value }).then((res) => {
  //       console.log('编辑-特殊字段-res:', res);
  //       if (res.data) {
  //         this.setState({
  //           specialFields: res.data,
  //         });
  //       }
  //       console.log("编辑-特殊字段数组", this.state.specialFields);
  //     }, (err) => {
  //       console.log('编辑-特殊字段-错误信息', err);
  //     });
  //   }
  // };

  showSpecialFields = () => {
    const arr = this.state.editSpecialArray.map((value, index) => {
      return (
        <div key={index}>
          {this.renderMap(value.fieldType, value.fieldName, value.fieldCode, value.isRequired, value.fieldValue, value.maxLength)}
        </div>
      );
    });
    return arr;
  }

  renderMap = (fieldType, fieldName, fieldCode, isRequired, fieldValue, maxLength) => {
    const formItemLayout = {
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 7
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 12
        },
        md: {
          span: 10
        }
      }
    };
    const { getFieldDecorator } = this.props.form;

    if (fieldType === '1') {
      return (
        <FormItem
          {...formItemLayout}
          label={fieldName}
        >
          {getFieldDecorator(`${fieldCode}`, {
            initialValue: fieldValue,
            rules: [{
              required: isRequired, message: `请输入${fieldName}`,
            }],
          })(
            <Input placeholder="请输入" maxLength="20" />
            )}
        </FormItem>
      );
    } else if (fieldType === '4') {
      return (
        <FormItem
          {...formItemLayout}
          label={fieldName}
        >
          {getFieldDecorator(`${fieldCode}`, {
            initialValue: fieldValue,
            rules: [{
              required: isRequired, message: `请选择${fieldName}`,
            }],
          })(
            <Select placeholder="请选择" className="sls-style">
              <Option value=" ">请选择</Option>
              {this.renderCertificateLevel()}
            </Select>
            )}
        </FormItem>
      );
    } else if (fieldType === '9') {
      return (
        <FormItem
          {...formItemLayout}
          label={fieldName}
        >
          {getFieldDecorator(`${fieldCode}`, {
            initialValue: moment(fieldValue, dateFormat),
            rules: [{
              required: isRequired, message: `请选择${fieldName}`,
            }],
          })(
            <DatePicker placeholder="请选择" style={{ width: '100%' }} />
            )}
        </FormItem>
      );
    }
  };

  //表单提交
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      console.log("editSpecialArray-编辑提交时候-特殊数组", this.state.editSpecialArray);
      if (!err) {
        console.log("values", values);

        const perCerId = this.state.currentId;//人员ID
        let list = [];
        console.log("editSpecialArray-编辑-特殊数组", this.state.editSpecialArray);
        if (values) {
          for (let [k, v] of Object.entries(values)) {
            this.state.editSpecialArray.map((val) => {
              if (val.fieldCode === k) {
                console.log("进入");

                if (typeof v === 'object') {
                  console.log("values[key]", k);
                  v = moment(v['_d']).format(dateFormat);
                  console.log("values[key]-vvv", v);
                  val.fieldValue = v;
                } else {
                  val.fieldValue = v;
                }
              }
              return true;
            });
          }
          list = this.state.editSpecialArray;
          // list.push(
          //   {
          //     fieldCode: 'perCerLevel',
          //     fieldValue: values.perCerLevel ? values.perCerLevel : '',//证书等级
          //   },
          //   {
          //     fieldCode: 'trainStartDate',
          //     fieldValue: values.trainStartDate ? values.trainStartDate.format('YYYY-MM-DD') : '',//培训开始日期
          //   },
          //   {
          //     fieldCode: 'trainEndDate',
          //     fieldValue: values.trainEndDate ? values.trainEndDate.format('YYYY-MM-DD') : '',//培训结束日期
          //   },
          //   {
          //     fieldCode: 'trainOrganName',
          //     fieldValue: values.trainOrganName ? values.trainOrganName : '',//培训单位
          //   },
          //   {
          //     fieldCode: 'pressIndoCardNumber ',
          //     fieldValue: values.pressIndoCardNumber ? values.pressIndoCardNumber : '',//"十指指纹按印卡号"
          //   },
          //   {
          //     fieldCode: 'certificateStartDate',
          //     fieldValue: values.certificateStartDate ? values.certificateStartDate.format('YYYY-MM-DD') : '',//有效期开始日期
          //   },
          //   {
          //     fieldCode: 'certificateEndDate',
          //     fieldValue: values.certificateEndDate ? values.certificateEndDate.format('YYYY-MM-DD') : '',//有效期结束日期
          //   },
          //   {
          //     fieldCode: 'gunProofCode',
          //     fieldValue: values.gunProofCode ? values.gunProofCode : '',//""持枪证枪型代码""
          //   },
          // );
        }
        console.log("list数组", list);
        list = JSON.stringify(list);
        console.log("list数组-字符串", list);

        const obj = {
          perCerId,
          perCerType: values.perCerType ? values.perCerType : '',//证书类型
          cerNo: values.cerNo ? values.cerNo : '',//证书编号
          licenceOrg: values.licenceOrg ? values.licenceOrg : '',//发证机关
          licenceOrgNo: values.licenceOrgNo ? values.licenceOrgNo : '',//发证机关编号
          licenceDate: values.licenceDate ? values.licenceDate.format('YYYY-MM-DD') : '',//发证日期
          //perCerLevel: values.perCerLevel ? values.perCerLevel : '',//证书等级
          list,
        };
        console.log("编辑-obj", obj);
        systemPerCerBaseInfoUpdate(obj).then((res) => {
          console.log("成功信息-编辑证书-保存：", res);
          message.success("保存成功！");
          this.setState({ editCertificateOpen: false });
          this.props.refreshList();
        }, (error) => {
          message.error(error);
          console.log("错误信息-编辑证书-保存：", error);
        });
      }
    });
  }
  //证书类型
  renderCertificateType = () => {
    return this.state.perCerType.map((val, key) => {
      return <Option key={key} value={val.codeValue + ""}>{val.label}</Option>;
    });
  };

  //证书等级
  renderCertificateLevel = () => {
    return this.state.perCerlevel.map((val, key) => {
      return <Option key={key} value={val.codeValue + ""}>{val.label}</Option>;
    });
  };

  /******************************render******************************/

  render() {
    const formItemLayout = {
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 7
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 12
        },
        md: {
          span: 10
        }
      }
    };
    const { getFieldDecorator } = this.props.form;

    return (
      <Box>
        <Drawer
          overlayColor="rgba(0, 0, 0,0)"
          right
          open={this.state.editCertificateOpen}
          noTouchClose
          width={600}
          zIndex={2}
          className="drawer-box"
          onChange={(editCertificateOpen) => {
            this.props.onChange(editCertificateOpen);
            this.setState({ editCertificateOpen });
          }}
        >
          <div className="drawer">
            <div className="drawer-header">证书编辑</div>
            <div className="drawer-content">
              <Form onSubmit={this.handleSubmit}>
                <FormItem
                  {...formItemLayout}
                  label="证书类型"
                >
                  {getFieldDecorator('perCerType', {
                    initialValue: this.state.editList.perCerType,
                    rules: [
                      { required: true, message: '请选择证书类型!' },
                    ],
                  })(
                    <Select disabled className="sls-style">
                      {this.renderCertificateType()}
                    </Select>
                    )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="证书编号"
                >
                  {getFieldDecorator('cerNo', {
                    initialValue: this.state.editList.cerNo,
                    rules: [{
                      required: true, message: '请输入证书编号',
                    }, {
                      pattern: /^([A-Za-z0-9])|(.){6,20}$/, message: '格式错误！',
                    }],
                  })(
                    <Input placeholder="请输入" maxLength="20" />
                    )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="发证机关:"
                >
                  {getFieldDecorator('licenceOrg', {
                    initialValue: this.state.editList.licenceOrg,
                    rules: [{
                      required: true, message: '请输入发证机关',
                    }
                      //   , {
                      //   validator: this.checkPhone
                      // }
                    ],
                  })(
                    <Input placeholder="请输入" maxLength="20" />
                    )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label=" 发证机关编号"
                >
                  {getFieldDecorator('licenceOrgNo', {
                    initialValue: this.state.editList.licenceOrgNo,
                    rules: [{
                      required: true, message: '请输入发证机关编号',
                    }, {
                      pattern: /^([A-Za-z0-9])|(.){6,20}$/, message: '格式错误！',
                    }],
                  })(
                    <Input placeholder="请输入" maxLength="20" />
                    )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="发证日期"
                >
                  {getFieldDecorator('licenceDate', {
                    initialValue: moment(this.state.editList.licenceDate, dateFormat),
                    rules: [{
                      type: 'object', required: true, message: '请选择证书发证日期',
                    }],
                  })(
                    <DatePicker placeholder="请选择证书发证日期" style={{ width: '100%' }} />
                    )}
                </FormItem>
                {this.showSpecialFields()}
              </Form>
            </div>
            <div className="drawer-footer">
              <Button onClick={() => this.setState({ editCertificateOpen: false })}>取消</Button>
              <Button type="primary" htmlType="submit" onClick={this.handleSubmit}>确认修改</Button>
            </div>
          </div>
        </Drawer>
      </Box>
    );
  }
}

/************************样式************************/

const Box = style.div`{
  .drawer-content{
    margin-top:28px;
  }
}`;